<?php

namespace app\home\controller;

use app\common\controller\Home;
use PHPMailer\PHPMailer\PHPMailer;
use think\Request;

class User extends Home
{
    public function __construct()
    {
        parent::__construct();
        $this->UserModel = model('User.User');
    }

    // 用户首页
    public function index()
    {
        // 获取用户的帖子
        $UserPost = model('Post.Post')->with('user')->where('userid', $this->LoginUser['id'])->select();

        // 获取用户的评论
        $UserComment = model('Post.Comment')->with('user', 'post')->where(['userid' => $this->LoginUser['id']])->select();


        $paramsid = $this->request->param('userid', $this->LoginUser['id']);
        $person = model("User.User")->where('id', $paramsid)->find();
        if (empty($person)) {
            $this->error("该用户不存在", url("home/index/index"), null, 1);
        }
        // 获取用户的帖子
        $PersonPost = model('Post.Post')->with('user')->where('userid', $person['id'])->select();
        // 获取用户的评论
        $PersonComment = model('Post.Comment')->with('user', 'post')->where(['userid' => $person['id']])->select();

        return $this->fetch('', [
            'UserPost' => $UserPost,
            'UserComment' => $UserComment,
            'person' => $person,
            'PersonPost' => $PersonPost,
            'PersonComment' => $PersonComment
        ]);
    }

    public function person()
    {
        return $this->fetch('', []);
    }

    // 个人资料
    public function profile()
    {
        $navtitle = '基本资料';

        if ($this->request->isPost()) {
            $action = $this->request->param('action', '');
            // halt($action);
            // 我的资料
            if ($action == 'profile') {
                $params = $this->request->param();
                $data = [
                    'id' => $this->LoginUser['id'],
                    'nickname' => $params['nickname'],
                    'sex' => $params['sex'],
                    'province' => $params['province'],
                    'city' => $params['city'],
                    'district' => $params['district'],
                    'content' => $params['content']
                ];
                $res = $this->UserModel->isUpdate(true)->save($data);
                if ($res == false) {
                    $this->error('更新失败');
                } else {
                    $this->success('更新成功', url('home/user/index'));
                }
            }
            // 头像
            if ($action == 'avatar') {
                $avatar = upload('avatar');
                // halt($avatar);
                if ($avatar['code'] == 0) {
                    $this->error($avatar['msg']);
                }
                $data = [
                    'id' => $this->LoginUser['id'],
                    'avatar' => $avatar['data']
                ];
                $res = $this->UserModel->isUpdate(true)->save($data);
                if ($res == false) {
                    @is_file('.' . $data['avatar']) && unlink('.' . $data['avatar']);
                    $this->error('更新头像失败');
                } else {
                    @is_file('.' . $this->LoginUser['avatar']) && unlink('.' . $this->LoginUser['avatar']);
                    $this->success('更新头像成功');
                }
            }
            // 密码 
            if ($action == 'setpwd') {
                // $params = $this->request->param();
                // halt($params);
                $old = $this->request->param('oldpass');
                $newpass = $this->request->param('newpass');
                $repass = $this->request->param('repass');
                $user = $this->UserModel->find($this->LoginUser['id']);
                if ($user == null) {
                    $this->error('请先登陆', null, null, 2);
                }
                $flagpass = md5($old . $this->LoginUser['salt']);
                if ($flagpass != $this->LoginUser['password']) {
                    $this->error('当前密码不正确');
                }
                if ($newpass != $repass) {
                    $this->error('密码前后不一致');
                }
                $salt = build_ranstr();
                $pwd = md5($newpass . $salt);
                $data = [
                    'id' => $this->LoginUser['id'],
                    'password' => $pwd,
                    'salt' => $salt
                ];
                $res = $this->UserModel->isUpdate(true)->save($data);
                if ($res == false) {
                    $this->error('密码修改失败');
                }
                $info = md5($this->LoginUser['id'] . $salt);
                cookie('LoginUser', $info);
                $this->success('密码修改成功');
                // $data = md5($User['id'] . $User['salt']);

            }
            // 封面
            if ($action == 'cover') {
                // $params = $this->request->param();
                $cover = upload('cover');
                // halt($cover);
                if ($cover['code'] == 0) {
                    $this->error($cover['msg']);
                }
                $data = [
                    'id' => $this->LoginUser['id'],
                    'cover' => $cover['data']
                ];
                $res = $this->UserModel->isUpdate(true)->save($data);
                if ($res == false) {
                    @is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
                    $this->error('更新封面失败');
                } else {
                    @is_file('.' . $this->LoginUser['cover']) && unlink('.' . $this->LoginUser['cover']);
                    $this->success('更新封面成功');
                }
            }
        }

        // 查询地区的省份
        $provinces = model('Region')->where(['grade' => 1])->select();

        // 查询市
        if ($this->LoginUser['province']) {
            $citys = model('Region')->where(['parentid' => $this->LoginUser['province']])->select();
        } else {
            $citys = [];
        }

        // 查询区
        if ($this->LoginUser['city']) {
            $districts = model('Region')->where(['parentid' => $this->LoginUser['city']])->select();
        } else {
            $districts = [];
        }

        return $this->fetch('', [
            'navtitle' => $navtitle,
            'provinces' => $provinces,
            'citys' => $citys,
            'districts' => $districts
        ]);
    }

    // 查询地区
    public function area()
    {
        if ($this->request->isAjax()) {
            $code = $this->request->param('code', '');
            $list = model('Region')->where(['parentid' => $code])->select();
            if (!$list) {
                $this->error('地区不存在');
            }
            $this->success('查询成功', null, $list);
        }
    }

    // 积分消费记录
    public function record()
    {
        $navtitle = '积分消费记录';

        $record = model('User.Record')->where('userid', $this->LoginUser['id'])->select();
        if (!$record) {
            $this->error("查询失败，请稍后再试");
        }
        $countarr = count($record);

        // 获取帖子  分页
        $RecordtList = model('User.Record')->where('userid', $this->LoginUser['id'])
            ->order('createtime', 'desc')->paginate(4, false, ['query' => Request::instance()->param()]);

        return $this->fetch('', [
            'navtitle' => '积分消费记录',
            'record' => $record,
            'countarr' => $countarr,
            'RecordtList' => $RecordtList
        ]);
    }
    // 我的帖子
    public function post()
    {
        $navtitle = '我的帖子';

        // 帖子记录
        $post = model('Post.Post')->with(['user'])->where('userid', $this->LoginUser['id'])->select();
        $postcount = count($post);

        // 收藏的帖子
        $collect = model("User.Collect")->with(['user', 'post'])->where('collect.userid', $this->LoginUser['id'])->select();
        $collectcount = count($collect);

        // halt($collect);
        return $this->fetch('', [
            'navtitle' => $navtitle,
            'post' => $post,
            'postcount' => $postcount,
            'collect' => $collect,
            'collectcount' => $collectcount
        ]);
    }

    // 发送邮箱
    public function email()
    {
        if ($this->request->isAjax()) {
            $email = $this->request->param('email', '');
            $user = $this->UserModel->where(['email' => $email])->find();
            if (!$user) {
                $this->error('邮箱不存在');
            }
            $Eamil = md5($user['email'] . $user['salt']);
            $content = "<a href='http://www.ask.com/home/index/auth?email=$Eamil'>点击认证</a>";
            $mail = new PHPMailer(true);
            // 开启SMTP服务
            $mail->isSMTP(true);
            // SMTP服务器  qq邮箱=>  smtp.qq.com
            $mail->Host = "smtp.163.com";
            // 开启认证
            $mail->SMTPAuth = true;
            // 开启支持html发送
            $mail->isHTML(true);
            // 账号
            $mail->Username = 'yjh023873@163.com';
            // 密码 => 开启SMTP时的授权码
            $mail->Password = 'NAXJCXKALSCDWBXD';
            // 端口   服务器需要465端口
            $mail->Port = 465;
            // 协议
            $mail->SMTPSecure = 'ssl';
            // 发件邮箱
            $mail->From = 'yjh023873@163.com';
            // 发件人名字
            $mail->FromName = 'ASK论坛';
            // 接收回复邮箱
            $mail->addReplyTo('yjh023873@163.com', 'NAXJCXKALSCDWBXD');
            // 收件人
            $mail->addAddress($user['email'], $user['nickname']);

            // 邮箱主题
            $mail->Subject = '账号认证';
            // 设置多少个字符换行  80字符
            $mail->WordWrap = 80;
            // 发送内容
            $mail->msgHTML($content);
            // 发送
            $res = $mail->send();
            if ($res === false) {
                $this->error('发送邮件失败');
            } else {
                $this->success('发送邮件成功');
            }
        }
    }
}
